package com.ruoyi.config;

import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private String bucketName;

    @Autowired
    private String urlPrefix;

    /**
     * 上传文件
     * @param file 文件对象
     * @param folder 上传到的文件夹
     * @return 文件访问URL
     */
    public String upload(MultipartFile file, String folder) {
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = folder + "/" + UUID.randomUUID().toString() + fileExtension;

            // 上传到OSS
            ossClient.putObject(bucketName, fileName, file.getInputStream());

            // 返回访问URL
            return urlPrefix + fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 删除文件
     * @param fileUrl 文件URL
     */
    public void delete(String fileUrl) {
        String fileName = fileUrl.replace(urlPrefix, "");
        ossClient.deleteObject(bucketName, fileName);
    }
}
